<template>
  <div class="model-cache-manager" v-if="showManager">
    <div class="cache-header">
      <h3>模型缓存管理</h3>
      <button class="close-btn" @click="closeManager">×</button>
    </div>
    
    <div class="cache-info">
      <div class="info-item">
        <span>缓存大小:</span>
        <span>{{ formatBytes(cacheSize) }}</span>
      </div>
      <div class="info-item">
        <span>已缓存模型:</span>
        <span>{{ cachedModels.length }}</span>
      </div>
    </div>

    <div class="cache-actions">
      <button @click="preloadAllModels" :disabled="isLoading">
        {{ isLoading ? '预加载中...' : '预加载所有模型' }}
      </button>
      <button @click="clearAllCache" :disabled="isLoading">
        清空所有缓存
      </button>
      <button @click="refreshCacheInfo">
        刷新信息
      </button>
    </div>

    <div class="model-list">
      <h4>模型列表</h4>
      <div class="model-item" v-for="model in allModels" :key="model.id">
        <div class="model-info">
          <span class="model-name">{{ model.name }}</span>
          <span class="model-size">{{ formatBytes(model.size || 0) }}</span>
          <span class="cache-status" :class="{ cached: isModelInCache(model.url) }">
            {{ isModelInCache(model.url) ? '已缓存' : '未缓存' }}
          </span>
        </div>
        <button 
          @click="preloadModel(model.url)" 
          :disabled="isModelInCache(model.url) || isLoading"
          class="preload-btn"
        >
          预加载
        </button>
      </div>
    </div>

    <div class="loading-indicator" v-if="isLoading">
      <div class="spinner"></div>
      <span>{{ loadingText }}</span>
    </div>
  </div>

  <button 
    v-if="!showManager" 
    @click="openManager" 
    class="cache-toggle-btn"
  >
    缓存管理
  </button>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useModelCache } from '@/utils/modelCacheManager'
import { getPreloadModels, BASE_MODELS, ENVIRONMENT_MAPS, ACTION_MODELS } from '@/config/models'

const { 
  preloadModel, 
  clearAllModelCache, 
  getCachedModels, 
  isModelCached, 
  getCacheSize 
} = useModelCache()

const showManager = ref(false)
const cacheSize = ref(0)
const cachedModels = ref([])
const isLoading = ref(false)
const loadingText = ref('')

const allModels = computed(() => [
  ...BASE_MODELS,
  ...ENVIRONMENT_MAPS,
  ...ACTION_MODELS
])

const openManager = () => {
  showManager.value = true
  refreshCacheInfo()
}

const closeManager = () => {
  showManager.value = false
}

const refreshCacheInfo = async () => {
  try {
    cacheSize.value = await getCacheSize()
    cachedModels.value = await getCachedModels()
  } catch (error) {
    console.error('Failed to refresh cache info:', error)
  }
}

const preloadAllModels = async () => {
  isLoading.value = true
  loadingText.value = '正在预加载所有模型...'
  
  try {
    const models = getPreloadModels()
    for (let i = 0; i < models.length; i++) {
      loadingText.value = `预加载中... ${i + 1}/${models.length}`
      await preloadModel(models[i])
    }
    await refreshCacheInfo()
  } catch (error) {
    console.error('Failed to preload models:', error)
  } finally {
    isLoading.value = false
  }
}

const clearAllCache = async () => {
  if (confirm('确定要清空所有模型缓存吗？')) {
    isLoading.value = true
    loadingText.value = '正在清空缓存...'
    
    try {
      await clearAllModelCache()
      await refreshCacheInfo()
    } catch (error) {
      console.error('Failed to clear cache:', error)
    } finally {
      isLoading.value = false
    }
  }
}

const isModelInCache = (url) => {
  return cachedModels.value.includes(url)
}

const formatBytes = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

onMounted(() => {
  refreshCacheInfo()
})
</script>

<style scoped>
.model-cache-manager {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
  max-height: 600px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  z-index: 10000;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.cache-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.cache-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cache-info {
  padding: 16px 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.cache-actions {
  padding: 0 20px 16px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.cache-actions button {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 12px;
}

.cache-actions button:hover:not(:disabled) {
  background: #f5f5f5;
}

.cache-actions button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.model-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px 16px;
}

.model-list h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
}

.model-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.model-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.model-name {
  font-size: 13px;
  font-weight: 500;
}

.model-size {
  font-size: 11px;
  color: #666;
}

.cache-status {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 3px;
}

.cache-status.cached {
  background: #e6f7ff;
  color: #1890ff;
}

.cache-status:not(.cached) {
  background: #fff2e8;
  color: #fa8c16;
}

.preload-btn {
  padding: 4px 8px;
  font-size: 11px;
  border: 1px solid #1890ff;
  border-radius: 3px;
  background: #1890ff;
  color: white;
  cursor: pointer;
}

.preload-btn:hover:not(:disabled) {
  background: #40a9ff;
}

.preload-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.loading-indicator {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.cache-toggle-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 10px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  z-index: 9999;
}

.cache-toggle-btn:hover {
  background: #40a9ff;
}
</style>

<style>
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
}
</style>